package com.alibaba.yinan.domain.task.event;

import com.alibaba.yinan.domain.task.service.lifecycle.TaskStateMachineHandler;
import com.alibaba.yinan.domain.task.Task;
import com.alibaba.yinan.domain.task.enums.TaskEvent;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;


/**
 * @ClassName TaskEventListener
 * @Author mengke
 * @create 2025/8/4 02:32
 * @Description
 */
@Slf4j
@Component
public class TaskEventListener {

    @Resource
    private TaskStateMachineHandler stateHandler;

    @Async
    @EventListener
    public void handle(TaskDomainEvent event) {
        Task task = event.getTask();
        log.info("监听到任务状态变化：任务ID: {}, 新状态: {}", task.getId(), task.getStatus());

        switch (task.getStatus()) {
            case COMPLETED:
                // 处理完成逻辑，如通知流程引擎
                log.info("任务完成，任务ID: {}", task.getId());
                break;

            case FAILED:
                // 发送报警通知等
                log.info("任务失败，任务ID: {}", task.getId());
                break;

            case DISPATCHED:
                // 已分配 → 自动进入执行
                log.info("任务已分配，任务ID: {}, 开始执行...", task.getId());
                task.changeState(TaskEvent.START, stateHandler);
                break;

            case RUNNING:
                log.info("任务执行中，任务ID: {}", task.getId());
                break;

            default:
                log.warn("未处理的任务状态: {}", task.getStatus());
        }
    }
}
